﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Entities;
using SqlSugar;
using Surging.Core.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Repository.Repositorys
{
    /// <summary>
    /// 环信用户联系表仓储层
    /// </summary>
    public class HxUserContactRepository : SqlSugarRepository<HxUserContactEntity, Guid>
    {
        private ISugarUnitOfWork _unitOfWork;
        public HxUserContactRepository(ISugarUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<HxUserContactEntity>> GetPageList(HxUserContactQueryDto input)
        {
            //var totalCount = 0;
            var pagePredict = _unitOfWork.QueryClient.Queryable<HxUserContactEntity>()
                .Where(it => it.IsDeleted == 0)
                .WhereIF(input.SelfUserId.HasValue, it => it.SelfUserId == input.SelfUserId)
                .WhereIF(input.SelfOrgId.HasValue, it => it.SelfOrgId == input.SelfOrgId)
                .WhereIF(!string.IsNullOrWhiteSpace(input.SelfHxUserName), it => it.SelfHxUserName == input.SelfHxUserName.Trim())
                .WhereIF(input.ContactSystemId.HasValue, it => it.ContactSystemId == input.ContactSystemId);
            //.OrderBy(it => it.Id, OrderByType.Desc)
            //.ToPageList(input.PageIndex, input.PageSize, ref totalCount);
            var totalCount = await pagePredict.CountAsync();
            var pageList = await pagePredict.OrderBy(it => it.LastContactTime, OrderByType.Desc).ToPageListAsync(input.PageIndex, input.PageSize);

            //var page = new PageDataList<HxUserContactEntity>(pageList)
            //{
            //    TotalCount = totalCount
            //};
            //return page;
            var page = new PageDataList<HxUserContactEntity>(totalCount, pageList, input.PageIndex, input.PageSize);
            return page;
        }


        /// <summary>
        /// 保存或更新联系人表
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> SaveOrUpdateContactFromMsgHistory(List<HxMsgHistoryEntity> list)
        {
            if (list == null|| list.Count==0)
            {
                return false;
            }
            foreach (var input in list)
            {
                #region From TO
                var entity = await GetBySelfAndContactHxUserName(input.FromHxUserName, input.ToHxUserName);
                if (entity == null)
                {
                    entity = new HxUserContactEntity();
                    entity.Id = Guid.NewGuid();
                    entity.SelfSystemId = input.FromSystemId;
                    entity.SelfUserId = input.FromUserId;
                    entity.SelfHxUserName = input.FromHxUserName;
                    entity.SelfNickName = input.FromNickName;
                    entity.SelfOrgId = input.FromOrgId;
                    entity.SelfOrgName = input.FromOrgName;
                    entity.SelfAvatar = input.FromAvatar;
                    entity.ContactSystemId = input.ToSystemId;
                    entity.ContactUserId = input.ToUserId;
                    entity.ContactHxUserName = input.ToHxUserName;
                    entity.ContactNickName = input.ToNickName;
                    entity.ContactOrgId = input.ToOrgId;
                    entity.ContactOrgName = input.ToOrgName;
                    entity.ContactAvatar = input.ToAvatar;
                    entity.LastContactUserId = input.ToUserId;
                    entity.LastContactTime = input.SendTime;
                    entity.LastContactMsg = input.MsgContent;
                    entity.IsDeleted = 0;
                    entity.Remark = "";
                    entity.CreatedTime = DateTime.Now;
                    entity.CreatedUserId = input.FromUserId;
                    entity.CreatedUserName = input.FromNickName;
                    await _unitOfWork.ModifyClient.Insertable(entity).ExecuteCommandAsync();
                }
                else
                {
                    entity.SelfNickName = input.FromNickName;
                    entity.SelfOrgId = input.FromOrgId;
                    entity.SelfOrgName = input.FromOrgName;
                    entity.SelfAvatar = input.FromAvatar;
                    entity.ContactNickName = input.ToNickName;
                    entity.ContactOrgId = input.ToOrgId;
                    entity.ContactOrgName = input.ToOrgName;
                    entity.ContactAvatar = input.ToAvatar;
                    entity.LastContactUserId = input.ToUserId;
                    entity.LastContactTime = input.SendTime;
                    entity.LastContactMsg = input.MsgContent;
                    await UpdateLastContact(entity);
                }
                #endregion

                #region TO From
                entity = await GetBySelfAndContactHxUserName(input.ToHxUserName, input.FromHxUserName);
                if (entity == null)
                {
                    entity = new HxUserContactEntity();
                    entity.Id = Guid.NewGuid();
                    entity.SelfSystemId = input.ToSystemId;
                    entity.SelfUserId = input.ToUserId;
                    entity.SelfHxUserName = input.ToHxUserName;
                    entity.SelfNickName = input.ToNickName;
                    entity.SelfOrgId = input.ToOrgId;
                    entity.SelfOrgName = input.ToOrgName;
                    entity.SelfAvatar = input.ToAvatar;
                    entity.ContactSystemId = input.FromSystemId;
                    entity.ContactUserId = input.FromUserId;
                    entity.ContactHxUserName = input.FromHxUserName;
                    entity.ContactNickName = input.FromNickName;
                    entity.ContactOrgId = input.FromOrgId;
                    entity.ContactOrgName = input.FromOrgName;
                    entity.ContactAvatar = input.FromAvatar;
                    entity.LastContactUserId = input.FromUserId;
                    entity.LastContactTime = input.SendTime;
                    entity.LastContactMsg = input.MsgContent;
                    entity.IsDeleted = 0;
                    entity.Remark = "";
                    entity.CreatedTime = DateTime.Now;
                    entity.CreatedUserId = input.FromUserId;
                    entity.CreatedUserName = input.FromNickName;
                    await _unitOfWork.ModifyClient.Insertable(entity).ExecuteCommandAsync();
                }
                else
                {
                    entity.SelfNickName = input.ToNickName;
                    entity.SelfOrgId = input.ToOrgId;
                    entity.SelfOrgName = input.ToOrgName;
                    entity.SelfAvatar = input.ToAvatar;
                    entity.ContactNickName = input.FromNickName;
                    entity.ContactOrgId = input.FromOrgId;
                    entity.ContactOrgName = input.FromOrgName;
                    entity.ContactAvatar = input.FromAvatar;
                    entity.LastContactUserId = input.FromUserId;
                    entity.LastContactTime = input.SendTime;
                    entity.LastContactMsg = input.MsgContent;
                    await UpdateLastContact(entity);
                }
                #endregion
            }
            return true;
        }
        /// <summary>
        /// 根据Id获取一个实体对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<HxUserContactEntity> GetBySelfAndContactHxUserName(string selfHxUserName,string contactHxUserName)
        {
            return await _unitOfWork.QueryClient.Queryable<HxUserContactEntity>().Where(it=>it.IsDeleted==0&&it.SelfHxUserName== selfHxUserName&&it.ContactHxUserName==contactHxUserName).FirstAsync();
        }


        /// <summary>
        /// 修改用户基本信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateLastContact(HxUserContactEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new {
                it.SelfNickName,
                it.SelfOrgId,
                it.SelfOrgName,
                it.SelfAvatar,
                it.ContactNickName,
                it.ContactOrgId,
                it.ContactOrgName,
                it.ContactAvatar,
                it.LastContactUserId,
                it.LastContactTime,
                it.LastContactMsg
            }).ExecuteCommandAsync() > 0;
            return result;
        }
    }
}
